﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Crossroad.Core.Configs;
using Crossroad.System.Admin.Attributes;
using Crossroad.System.Admin.Dto;
using Crossroad.System.Admin.Model;
using Crossroad.System.Admin.Service;
using Crossroad.System.Admin.Service.Impl;
using Crossroad.System.Api;
using Crossroad.Utils.Extensions;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Crossroad.System.Admin.Controller
{
    /// <summary>
    /// 系统菜单
    /// </summary>
    [Route("api/system/admin/menus")]
    public class MenuController : BaseApi
    {
        private readonly MenuService menuService;

        public MenuController(
            IMenuService menuServiceIpt
        )
        {
            menuService = menuServiceIpt as MenuService;
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="keywords"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="typeId"></param>
        /// <param name="roleId">角色关联菜单时传值</param>
        /// <returns></returns>
        [HttpGet]
        public object GetList(
            int? pageIndex = null,
            int? pageSize = null,
            string keywords = "",
            int? typeId = null,
            int? roleId = null
        )
        {
            //无分页列表查询
            if (pageIndex == null && pageSize == null)
                return menuService.GetList(queryable =>
                {
                    queryable
                        .OrderBy(a => a.sort, OrderByType.Asc)
                        .OrderBy(a => a.createTime, OrderByType.Desc);

                    if (typeId.NotNull())
                        queryable.Where(a => a.typeId == typeId);
                    if (keywords.Contains())
                        queryable.Where(a => SqlFunc.Contains(a.label, keywords));
                }, roleId);

            //有分页列表查询
            pageIndex = pageIndex ?? 1;
            pageSize = pageSize ?? AppConfig.DEFAULT_PAGE_SIZE;

            return menuService.GetPaging(pageIndex.Value, pageSize.Value, queryable =>
            {
                queryable
                   .OrderBy(a => a.sort, OrderByType.Asc)
                   .OrderBy(a => a.createTime, OrderByType.Desc);

                if (typeId.NotNull())
                    queryable.Where(a => a.typeId == typeId);
                if (keywords.Contains())
                    queryable.Where(a => SqlFunc.Contains(a.label, keywords));
            });
        }

        /// <summary>
        /// 查询树节点
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        [Permission("admin/menu/index/")]
        [HttpGet("tree")]
        public object TreeList(int typeId = 0)
        {
            var userApp = CurrentUserApp;

            var idList = menuService.GetIdListByRole(userApp.roleId, typeId);
            var list = menuService.GetList(queryable =>
                queryable
                    .In(a => a.id, idList)
                    .OrderBy(a => a.sort)
            );
            var treeList = list.FindAll(m => m.layerNum == 1);
            treeList.ForEach(item =>
            {
                var children = list.FindChildren(item);
                if (children.NotNull())
                    item.children = children;
            });

            return treeList;
        }

        /// <summary>
        /// 新增一个系统菜单
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [HttpPost]
        public object CreateAt(
            [FromBody] MenuDto parameter
        )
        {
            if (!parameter.optionList.IsNullOfEmpty())
            {
                parameter.optionList.ForEach(item =>
                    {
                        if (item.Trim().Length > 0)
                            parameter.optionIds += $"{item},";
                    }
                 );
                if (!parameter.optionIds.IsNullOrEmpty())
                    parameter.optionIds = parameter.optionIds.Insert(0, ",");
            }

            var model = new Menu
            {
                creatorId =  CurrentUser.id
            };
            parameter.CopyTo(model);

            return menuService.CreateAt(model);
        }

        /// <summary>
        /// 修改指定系统菜单
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="id">系统菜单的id</param>
        /// <returns></returns>
        [HttpPatch("{id}")]
        public object UpdateAt(
            [FromBody] MenuDto parameter,
            int id
        )
        {
            parameter.id = id;
            parameter.updatorId = CurrentUser.id;
            if (!parameter.optionList.IsNullOfEmpty())
            {
                parameter.optionList.ForEach(item =>
                    {
                        if (item.Trim().Length > 0)
                            parameter.optionIds += $"{item},";
                    }
                 );
                if (!parameter.optionIds.IsNullOrEmpty())
                    parameter.optionIds = parameter.optionIds.Insert(0, ",");
            }

            return menuService.UpdateAt(parameter);
        }

        /// <summary>
        /// 删除一个系统菜单
        /// </summary>
        /// <param name="id"></param>
        [HttpDelete("{id}")]
        public object DeleteAt(int id)
        {
            menuService.DeleteAt(new MenuDto
            {
                id = id
            });

            return true;
        }


    }
}